package com.ruitu.health_2.ui.common;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.androidkun.xtablayout.XTabLayout;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health_2.R;
import com.ruitu.health_2.mvp.model.VideoModel;
import com.ruitu.health_2.mvp.presenter.VideoPresenter;
import com.ruitu.health_2.ui.adapter.HorizonProListAdapter;
import com.ruitu.health_2.ui.fragment.VideoDetail1Fragment;
import com.ruitu.health_2.ui.fragment.VideoDetail2Fragment;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.bean.product.VideoDetial;
import com.ruitu.router_module.support.util.TimeUtil;
import com.ruitu.router_module.support.view.OnTabSelectedListenerImpl;

import java.util.ArrayList;
import java.util.List;

import androidx.core.widget.ContentLoadingProgressBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class VideoDetailActivity extends BaseActivity<VideoPresenter.VideoDetailP, VideoModel.VideoDetailM>
        implements HandlerUtil.OnReceiveMessageListener {
    private ImageView iv_back;
    private VideoView vv_video;
    private RelativeLayout rl_player;// 播放器的布局
    private SeekBar seek_bar;// 进度条
    private TextView tv_time, tv_total_time;// 播放时间,总时间
    private TextView tv_1, tv_2, tv_3, tv_4, tv_5;// 播放 暂停 停止 试看 全屏
    private ImageView iv_play, iv_pause, iv_full_screen, iv_full_screen_quit;// 播放 暂停 全屏 退出全屏
    private LinearLayout rl_progress;// 缓冲布局
    private ContentLoadingProgressBar progress_bar;// 缓冲进度条
    private TextView tv_hint, tv_title;// 提示文字,标题
    private TextView tv_login, tv_buy;// 登录, 购买
    private LinearLayout ll_control;// 控制面板按钮
    private RelativeLayout rl_content, rl_title, rl_control;// 播放器下面的内容部分,标题,控制按钮
    private XTabLayout tab;// 选项卡

    private VideoDetial videoDetail;// 请求得到的视频详细数据
    private List<ProHome> proList = new ArrayList<>();// 相关的商品列表
    private RecyclerView rcv_pro;// 横向的商品列表
    private HorizonProListAdapter adapter;// 商品列表的adapter

    private String videoUrl = "";
    private String videoId;// 传过来的视频对象

    private static final int TIME = 3;
    private int HIDE_TIME = TIME;// 隐藏控制按钮倒计时
    private HandlerUtil.HandlerHolder handler;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_video_detail;
    }

    @SuppressWarnings(value = "all")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        vv_video = findViewById(R.id.vv_video);
        iv_back = findViewById(R.id.iv_back);
        rl_player = findViewById(R.id.rl_player);
        seek_bar = findViewById(R.id.seek_bar);
        ll_control = findViewById(R.id.ll_control);
        rl_content = findViewById(R.id.rl_content);
        rl_title = findViewById(R.id.rl_title);
        rl_control = findViewById(R.id.rl_control);
        tv_time = findViewById(R.id.tv_time);
        tv_total_time = findViewById(R.id.tv_total_time);
        tv_1 = findViewById(R.id.tv_1);
        tv_2 = findViewById(R.id.tv_2);
        tv_3 = findViewById(R.id.tv_3);
        tv_4 = findViewById(R.id.tv_4);
        tv_5 = findViewById(R.id.tv_5);
        iv_play = findViewById(R.id.iv_play);
        iv_pause = findViewById(R.id.iv_pause);
        iv_full_screen = findViewById(R.id.iv_full_screen);
        iv_full_screen_quit = findViewById(R.id.iv_full_screen_quit);
        rcv_pro = findViewById(R.id.rcv_pro);
        tab = findViewById(R.id.tab);
        rl_progress = findViewById(R.id.rl_progress);
        progress_bar = findViewById(R.id.progress_bar);
        tv_hint = findViewById(R.id.tv_hint);
        tv_title = findViewById(R.id.tv_title);
        tv_login = findViewById(R.id.tv_login);
        tv_buy = findViewById(R.id.tv_buy);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            videoId = bundle.getString("videoId");
            videoUrl = bundle.getString("videoUrl");
            Logg.i("videoUrl = " + videoUrl);
        }

        handler = new HandlerUtil.HandlerHolder(this);
//        MediaController controller = new MediaController(this);
//        vv_video.setMediaController(controller);
        setListeners();

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_player.getLayoutParams();
        params.width = ScreenUtils.getScreenWidth();
        params.height = params.width * 9 / 16;
        rl_player.setLayoutParams(params);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//默认先给个竖屏

        setVideoHint("视频信息加载中");
        reqData(videoId);
    }

    // 请求视频详情
    public void reqData(String id) {
        String memberId = CommonUtils.isLogin() ? AppHolder.instance().getUser().getId() : "";
        p.reqVideoDetail(id, memberId);
        showProgress();
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {
            videoDetail = (VideoDetial) data;

            tab.removeAllTabs();
            tab.addTab(tab.newTab().setText("相关视频"), 0);
            tab.addTab(tab.newTab().setText("艺人介绍"), 1);

            tv_title.setText(videoDetail.getTitle());
            videoUrl = videoDetail.getVideo();
            if (!TextUtils.isEmpty(videoUrl)) {
                setUrl();
                setPlayListener();// 设置播放监听

                progress_bar.setVisibility(View.VISIBLE);
                tv_login.setVisibility(View.GONE);
                tv_buy.setVisibility(View.GONE);
                setVideoHint("视频正在缓冲");
            } else {
                if (TextUtils.equals("0", videoDetail.getStatus())) {// 0 未购买 1 已购买 2 未登录 3 免费
                    progress_bar.setVisibility(View.GONE);
                    tv_login.setVisibility(View.GONE);
                    tv_buy.setVisibility(View.VISIBLE);
                    setVideoHint("付费视频,购买才能观看");
                } else if (TextUtils.equals("2", videoDetail.getStatus())) {
                    progress_bar.setVisibility(View.GONE);
                    tv_login.setVisibility(View.VISIBLE);
                    tv_buy.setVisibility(View.GONE);
                    setVideoHint("尚未登录,登录才能观看");
                } else {

                }
            }

            setTabFragment(tab.getTabAt(tab.getSelectedTabPosition()));

            proList = videoDetail.getGoodsAboutVideo();
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setOrientation(RecyclerView.HORIZONTAL);
            adapter = new HorizonProListAdapter(this);
            rcv_pro.setLayoutManager(manager);
            rcv_pro.setAdapter(adapter);
            adapter.setDataList(proList);

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rcv_pro.getLayoutParams();
            if (isDataEmpty(proList)) {
                params.topMargin = 0;
            } else {
                params.topMargin = SizeUtils.dp2px(10);
            }
            rcv_pro.setLayoutParams(params);
        }
    }

    private void setListeners() {
        setOnClickListener(iv_back, tv_1, tv_2, tv_3, tv_4, tv_5, iv_play, iv_pause, iv_full_screen
                , iv_full_screen_quit, tv_login, tv_buy);
        tab.addOnTabSelectedListener(new OnTabSelectedListenerImpl() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                try {
                    setTabFragment(tab);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        vv_video.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                showCtrlAndResetTime();
                return false;
            }
        });
    }

    // 根据tab切换fragment
    private void setTabFragment(XTabLayout.Tab tab) {
        int tabIndex = tab.getPosition();
        if (tabIndex == 0) {
            getSupportFragmentManager().beginTransaction().replace(R.id.rl_container, VideoDetail1Fragment.newInstance(videoDetail), "f0").commitAllowingStateLoss();
            Arad.bus.post(new EventModel(19110760, null));
        }
        if (tabIndex == 1) {
            getSupportFragmentManager().beginTransaction().replace(R.id.rl_container, VideoDetail2Fragment.newInstance(videoDetail), "f1").commitAllowingStateLoss();
            Arad.bus.post(new EventModel(19110761, null));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == iv_back) {
            onBackPressed();
        }
        if (v == tv_1 || v == iv_play) {// 播放
            if (CommonUtils.isLoginToActivity(this)) {
                if (null == videoDetail) {
                    ToastUtils.showShortSafe("视频详情加载中");
                    return;
                }
                if (TextUtils.equals(videoDetail.getChargingSwitch(), "0") ||
                        TextUtils.equals("1", videoDetail.getStatus())) {// 免费或已购买
                    if (!isPrepared) {
                        ToastUtils.showShortSafe("加载中,请稍候重试");
                        return;
                    }
                    start();
                } else {
                    ToastUtils.showShortSafe("收费视频,请先购买");
                }
            } else {
                ToastUtils.showShortSafe("请先登录");
            }
            showCtrlAndResetTime();
        }
        if (v == tv_2 || v == iv_pause) {// 暂停
            iv_play.setVisibility(View.VISIBLE);
            iv_pause.setVisibility(View.GONE);
            pause();
            showCtrlAndResetTime();
        }
        if (v == tv_3) {// 停止
            stop();
        }
        if (v == tv_4) {// 试看
            startOnlyHead();
        }
        if (v == tv_5 || v == iv_full_screen) {// 全屏
            if (!isPrepared) {
                ToastUtils.showShortSafe("视频加载中...");
                return;
            }
            fullScreen();
            showCtrlAndResetTime();
        }
        if (v == iv_full_screen_quit) {
            if (!isPrepared) {
                ToastUtils.showShortSafe("视频加载中...");
                return;
            }
            fullScreen();
            showCtrlAndResetTime();
        }
        if (v == tv_login) {
            CommonUtils.isLoginToActivity(this);
        }
        if (v == tv_buy) {
            ToastUtils.showShortSafe("购买视频");
        }
    }

    private void setFullIconState(boolean isFull) {
        if (isFull) {
            iv_full_screen.setVisibility(View.GONE);
            iv_full_screen_quit.setVisibility(View.VISIBLE);
        } else {
            iv_full_screen.setVisibility(View.VISIBLE);
            iv_full_screen_quit.setVisibility(View.GONE);
        }
    }

    private boolean isPlayHead = false;// 是否是试看
    private Integer sMillis = 10000;// 试看的时间毫秒值
    private boolean isPrepared = false;
    private int currVideoWidth = 0;//当前视频宽
    private int currVideoHeight = 0;//当前视频高

    private void setUrl() {
        if (TextUtils.isEmpty(videoUrl)) {
            setVideoHint("视频信息有误");
            ToastUtils.showShortSafe("视频信息有误");
            return;
        }
        vv_video.setVideoURI(Uri.parse(videoUrl));// 装载播放地址
    }

    private void start() {
        if (isPrepared) {
            if (isPlayHead && vv_video.getCurrentPosition() >= sMillis) {// 是试看
                ToastUtils.showShortSafe("试看" + sMillis + "毫秒结束");
            } else {
                vv_video.start();
                iv_play.setVisibility(View.GONE);
                iv_pause.setVisibility(View.VISIBLE);
                handler.sendEmptyMessage(2020031051);
            }
        } else {
            ToastUtils.showShortSafe("视频加载中,请稍候重试");
        }

        handler.removeMessages(2019102551);
        handler.sendEmptyMessage(2019102551);
    }

    private void pause() {
        vv_video.pause();
    }

    public void stop() {
        vv_video.setBackgroundColor(Color.parseColor("#000000"));
        vv_video.stopPlayback();
        vv_video.setVideoURI(null);
        isPrepared = false;

        rl_progress.setVisibility(View.VISIBLE);
        progress_bar.setVisibility(View.VISIBLE);
        tv_login.setVisibility(View.GONE);
        tv_buy.setVisibility(View.GONE);
        setVideoHint("视频信息加载中");
    }

    private void startOnlyHead() {
        isPlayHead = !isPlayHead;
        if (isPlayHead) {
            ToastUtils.showShortSafe("已开启试看");
            tv_4.setText("关闭试看");
        } else {
            ToastUtils.showShortSafe("已关闭试看");
            tv_4.setText("试看");
        }

        handler.removeMessages(2019102551);
        handler.sendEmptyMessage(2019102551);
    }

    @SuppressWarnings(value = "all")
    private void fullScreen() {
        //判断当前屏幕方向
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setFullIconState(false);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setFullIconState(true);
        }
    }

    @SuppressWarnings(value = "all")
    @Override
    public void onBackPressed() {//点击返回的时候先切换竖屏
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            setFullIconState(false);
        } else {
            super.onBackPressed();
        }
    }

    @Override//横竖屏切换的时候执行
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setVideoViewSize(isScreenPortrait());
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            rl_content.setVisibility(View.GONE);
        } else {
            rl_content.setVisibility(View.VISIBLE);
        }
    }

    private void setVideoViewSize(boolean isPortrait) {//设置VideoView的尺寸
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rl_player.getLayoutParams();
        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) vv_video.getLayoutParams();
        if (isPortrait) {
            params.width = ScreenUtils.getScreenWidth();
            params.height = params.width * 9 / 16;

            params2.height = params.height;
            params2.width = currVideoWidth * params2.height / currVideoHeight;
            params2.addRule(RelativeLayout.CENTER_IN_PARENT);

        } else {
            params.width = ScreenUtils.getScreenWidth();
            params.height = ScreenUtils.getScreenHeight();

            params2.height = ScreenUtils.getScreenHeight();
            params2.width = currVideoWidth * params2.height / currVideoHeight;
            params2.addRule(RelativeLayout.CENTER_IN_PARENT);

        }
        rl_player.setLayoutParams(params);
        vv_video.setLayoutParams(params2);
    }

    private boolean isScreenPortrait() {//屏幕是否是竖屏
        return getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    private void setPlayListener() {
        handler.removeMessages(2019102551);
        vv_video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                isPrepared = true;
                start();

                seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (fromUser) {
                            if (isPlayHead && progress >= sMillis) {// 是试看
                                ToastUtils.showShortSafe("该视频只允许试看" + sMillis + "毫秒");
                                seekBar.setProgress(sMillis);
                                pause();
                            }
                            vv_video.seekTo(seekBar.getProgress());
                            tv_time.setText(TimeUtil.getMinAndSec(vv_video.getCurrentPosition()));
                            showCtrlAndResetTime();
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                    }
                });
            }
        });
        vv_video.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                rl_progress.setVisibility(View.GONE);
                vv_video.setBackgroundColor(Color.parseColor("#00000000"));
                showCtrlAndResetTime();

                seek_bar.setMax(vv_video.getDuration());
                tv_total_time.setText(TimeUtil.getMinAndSec(vv_video.getDuration()));
                handler.sendEmptyMessage(2019102551);

                currVideoWidth = mp.getVideoWidth();
                currVideoHeight = mp.getVideoHeight();
                setVideoViewSize(isScreenPortrait());
                return false;
            }
        });
    }

    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 2019102551) {// 视频播放
            if (isPlayHead) {// 试看
                handler.removeMessages(2019102551);
                if (vv_video.getCurrentPosition() >= sMillis) {
                    vv_video.seekTo(sMillis);
                    seek_bar.setProgress(vv_video.getCurrentPosition());
                    pause();
                    ToastUtils.showShortSafe("试看" + sMillis + "毫秒结束");
                } else {
                    handler.sendEmptyMessageDelayed(2019102551, 200);
                }
            } else {
                handler.removeMessages(2019102551);
                handler.sendEmptyMessageDelayed(2019102551, 200);
            }

            seek_bar.setProgress(vv_video.getCurrentPosition());
            tv_time.setText(TimeUtil.getMinAndSec(vv_video.getCurrentPosition()));
        }
        if (msg.what == 2020031051) {// 隐藏控制按钮倒计时
            handler.removeMessages(2020031051);
            if (HIDE_TIME <= 0) {
                showOrHideCtrl(false);
            } else {
                HIDE_TIME--;
                handler.sendEmptyMessageDelayed(2020031051, 1000);
            }
        }
    }

    private void setVideoHint(String txt) {
        tv_hint.setText(txt);
    }

    private void showOrHideCtrl(boolean isShow) {
        if (isShow) {
            rl_title.setVisibility(View.VISIBLE);
            rl_control.setVisibility(View.VISIBLE);
        } else {
            rl_title.setVisibility(View.GONE);
            rl_control.setVisibility(View.GONE);
        }
    }

    // 显示控制按钮一段时间后隐藏
    private void showCtrlAndResetTime() {
        showOrHideCtrl(true);
        HIDE_TIME = TIME;
        handler.sendEmptyMessage(2020031051);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != vv_video) {
            vv_video.stopPlayback();
            handler.removeMessages(2019102551);
        }
    }
}